package com.ruoyi.web.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import com.ruoyi.system.mapper.H5RegisterMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.web.domain.AishandongUser;
import com.ruoyi.web.domain.IShandongNatureUserInfo;
import com.ruoyi.web.domain.WorkEnterpriseUser;
import com.ruoyi.web.domain.dto.AiShanDongUserEncodeInfoDto;
import com.ruoyi.web.service.AiShanDongSsoService;
import com.ruoyi.web.service.NatureUserInfoService;
import com.ruoyi.web.service.WorkEnterpriseUserService;
import com.ruoyi.web.util.AESUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * description:
 * auth fcb
 * date 2025-04-09 14:44
 **/
@Service
@Slf4j
public class AiShanDongSsoServiceImpl implements AiShanDongSsoService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private H5RegisterMapper h5RegisterMapper;

    @Autowired
    private WorkEnterpriseUserService workEnterpriseUserService;

    @Autowired
    private NatureUserInfoService natureUserInfoService;

    /**
     * 爱山东的单点登录
     *
     * @param dto 加密后的用户数据
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult ssoLogin(AiShanDongUserEncodeInfoDto dto) {
        try {
        String cipherText = dto.getCipherText();
//        //两次解密，先SM2，再AES
//        //SM2解密
//        BCECPrivateKey privateKey = (BCECPrivateKey) SM2Utils.loadPrivateKey(SM2Utils.getSM2PrivateKey());
//        byte[] cipherTextBytes = Base64.getDecoder().decode(cipherText);
//        byte[] sm2Decrypted = SM2Utils.decrypt(cipherTextBytes, privateKey);

        //AES解密
        String aesDecrypted = AESUtils.decryptHex(cipherText, AESUtils.getAESSecretKey());
//        log.info("明文 -> {}", aesDecrypted);
        ObjectMapper om = new ObjectMapper();
        AishandongUser aishandongUser = om.readValue(aesDecrypted, AishandongUser.class);

//        if(StringUtils.isEmpty(dto.getEncodeUserInfo())) {
//        AishandongUser aishandongUser = dto.getAishandongUser();
        if(aishandongUser == null) {
            throw new ServiceException("用户信息为空");
        }
        if (StrUtil.isBlank(aishandongUser.getCornumber())) {
            // 代表该爱山东用户是个人用户
            // 存储或更新爱山东用户信息
            IShandongNatureUserInfo iShandongNatureUserInfo = new IShandongNatureUserInfo();
            BeanUtils.copyProperties(aishandongUser, iShandongNatureUserInfo);
            natureUserInfoService.saveOrUpdateIShandongUserInfo(iShandongNatureUserInfo);

            // 查询该用户是否已绑定企业
            String uuid = aishandongUser.getUuid();
            WorkEnterpriseUser enterpriseUser = workEnterpriseUserService.getOne(new LambdaQueryWrapper<WorkEnterpriseUser>().eq(WorkEnterpriseUser::getNatureUserUuid, uuid));
            if (enterpriseUser == null) {
                AjaxResult ajax = AjaxResult.success();
                ajax.put(Constants.TOKEN, "");
                ajax.put("isNew", "1");
                ajax.put("uuid", uuid);
                return ajax;
            } else {
                String token = sysLoginService.login(enterpriseUser.getUnicode(), "", "", "", UserDetailsServiceImpl.AI_SHAN_DONG_SSO_FLAG);
                AjaxResult ajax = AjaxResult.success();
                ajax.put(Constants.TOKEN, token);
                ajax.put("isNew", "0");
                ajax.put("uuid", "");
                return ajax;
            }
        }
//            AishandongUser aishandongUser = JSONObject.parseObject(dto.getEncodeUserInfo(), AishandongUser.class);
            // 判断用户是否存在
            String cornumber = aishandongUser.getCornumber();
            SysUser sysUser = sysUserMapper.checkUserNameUnique(cornumber);
            // 自动登录无需校验密码，并创建token
            if(sysUser != null) {
                String token = sysLoginService.login(sysUser.getUserName(), "", "", "", UserDetailsServiceImpl.AI_SHAN_DONG_SSO_FLAG);
                sysUserMapper.update(new LambdaUpdateWrapper<SysUser>().eq(SysUser::getUserId, sysUser.getUserId()).set(SysUser::getIShandongLoginname, aishandongUser.getLoginname()).set(SysUser::getLoginSource, dto.getLoginSource()));
                AjaxResult ajax = AjaxResult.success();
                ajax.put(Constants.TOKEN, token);
                return ajax;
            }else {
                String msg = "";
                // 新建用户
                SysUser user = new SysUser();
                user.setUserName(cornumber);
                user.setNickName(aishandongUser.getCorname());
                String password = cornumber;
                if (cornumber.length() >= 6) {
                    password = cornumber.substring(cornumber.length() - 6);
                }
                user.setPassword(SecurityUtils.encryptPassword(password));
                user.setRemark("企业人员");
                user.setIShandongLoginname(aishandongUser.getLoginname());
                user.setLoginSource(dto.getLoginSource());
                boolean regFlag = sysUserMapper.insertUser(user) > 0;
                if (!regFlag)
                {
                    msg = "注册失败,请联系系统管理人员";
                }
                else
                {
                    // 查询新的用户id，设置一个普通角色
                    Long userId = h5RegisterMapper.queryRegisterUserId(user.getUserName());
                    if(userId == null) {
                        msg = "注册失败,请联系系统管理人员";
                    }
                    else {
                        // 普通角色
                        h5RegisterMapper.insertRegisterUserRole(userId, 2L);
                        AsyncManager.me().execute(AsyncFactory.recordLogininfor(aishandongUser.getCorname(), Constants.REGISTER, MessageUtils.message("user.register.success")));

                    }
                }
                if (StringUtils.isNotEmpty(msg)) {
                    return AjaxResult.error(msg);
                } else {
                    String token = sysLoginService.login(cornumber, "", "", "", UserDetailsServiceImpl.AI_SHAN_DONG_SSO_FLAG);
                    AjaxResult ajax = AjaxResult.success();
                    ajax.put(Constants.TOKEN, token);
                    ajax.put("isNew", "0");
                    ajax.put("uuid", "");
                    return ajax;
                }
            }
        }catch (Exception e) {
            log.error("【爱山东单点登录异常】: {}", ExceptionUtil.getExceptionMessage(e));
        }
        return AjaxResult.error("登录异常");
    }
}
